use super::{ConnReceiver, ConnSender};
use crate::common::thread;
use async_ach_spsc as spsc;
use nrf_softdevice::ble::*;
use nrf_softdevice::raw;
use nrf_softdevice::Softdevice;

#[rustfmt::skip]
const ADV_DATA:&[u8] = &[
    0x02, 0x01, raw::BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE as u8,
    0x05, 0x09, b'u', b'n', b'm', b'p',
    0x04, 0xFF, 0x64, 0x64, 0x02,
];

pub fn start_adv() -> ConnReceiver {
    let (tx, rx) = spsc::channel();
    thread::spawn(adv(tx));
    rx
}

#[embassy::task]
async fn adv(mut tx: ConnSender) -> ! {
    let sd = unsafe { Softdevice::steal() };
    let mut random = [0];

    loop {
        let _err = getrandom::getrandom(&mut random);
        let config = peripheral::Config {
            primary_phy: Phy::M1,
            secondary_phy: Phy::M1,
            tx_power: TxPower::Minus4dBm,
            timeout: None,
            max_events: Some(10 + random[0] % 10),
            interval: 1600, //1s
        };
        let adv = peripheral::ConnectableAdvertisement::ExtendedNonscannableUndirected {
            adv_data: ADV_DATA,
        };
        let result = peripheral::advertise_connectable(sd, adv, &config).await;
        if let Ok(conn) = result {
            tx.send(conn).await;
        }
    }
}
